package live.zs.excelurltoimg.utils;

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.text.DecimalFormat;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * @author madison
 * {@code @description}
 * {@code @date} 2023/12/16 17:24
 */
public class FileUtils {

    private static final Logger logger = LoggerFactory.getLogger(FileUtils.class);

    private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    public static void unzip(String zipFilePath, String destDirectory) throws IOException {
        try (ZipFile zipFile = new ZipFile(new File(zipFilePath))) {
            Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
            while (entries.hasMoreElements()) {
                ZipArchiveEntry entry = entries.nextElement();
                File entryDestination = new File(destDirectory, entry.getName());
                if (entry.isDirectory()) {
                    entryDestination.mkdirs();
                } else {
                    entryDestination.getParentFile().mkdirs();
                    try (InputStream in = zipFile.getInputStream(entry);
                         OutputStream out = new FileOutputStream(entryDestination)) {
                        IOUtils.copy(in, out);
                    }
                }
            }
        }
    }

    public static void unzipJava(String zipFilePath, String destDir) throws Exception {
        FileInputStream fis;
        // 缓冲区大小
        byte[] buffer = new byte[1024];
        fis = new FileInputStream(zipFilePath);
        ZipInputStream zis = new ZipInputStream(fis);
        ZipEntry ze = zis.getNextEntry();
        while (ze != null) {
            String fileName = ze.getName();
            File newFile = new File(destDir + File.separator + fileName);
            // 创建所有非存在的父文件夹
            new File(newFile.getParent()).mkdirs();
            FileOutputStream fos = new FileOutputStream(newFile);
            int len;
            while ((len = zis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
            fos.close();
            // 关闭当前ZipEntry
            zis.closeEntry();
            ze = zis.getNextEntry();
        }
        // 关闭最后一个ZipEntry
        zis.closeEntry();
        zis.close();
        fis.close();
    }


    public static String containsExcelFiles(String directoryPath) {
        File dir = new File(directoryPath);

        // 确保这是一个目录
        if (!dir.isDirectory()) {
            logger.info("{} 不是一个有效的目录！", directoryPath);
            return "";
        }

        // 创建一个文件名过滤器，只接受以.xls或.xlsx结尾的文件
        FilenameFilter filter = new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return name.toLowerCase().endsWith(".xls") || name.toLowerCase().endsWith(".xlsx");
            }
        };

        // 列出所有符合条件的文件
        String[] excelFiles = dir.list(filter);
        logger.info("excelFiles:{}", Arrays.toString(excelFiles));

        // 检查是否存在Excel文件
        return excelFiles != null && excelFiles.length > 0 ? directoryPath + excelFiles[0] : "";
    }

    public static String getFileNameWithoutExtension(String originalFilename) {
        if (originalFilename == null || originalFilename.isEmpty()) {
            return "";
        }

        // 查找最后一个点的位置
        int dotIndex = originalFilename.lastIndexOf('.');
        if (dotIndex == -1) {
            // 没有扩展名
            return originalFilename;
        } else {
            // 返回不包含扩展名的文件名
            return originalFilename.substring(0, dotIndex);
        }
    }

    public static void checkFileExists(String path) {
        File file = new File(path);
        if (!file.exists()) {
            boolean mkdirs = file.mkdirs();
            logger.info("mkdir path:{}", mkdirs);
        }
    }

    public static String getCellValue(Cell cell) {
        if (cell == null) {
            return null;
        }
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue().replaceAll("\\s*", "");
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return dateTimeFormatter.format(cell.getLocalDateTimeCellValue());
//                    return cell.getDateCellValue().toString().replaceAll("\\s*", "");
                } else {
//                    return String.valueOf(cell.getNumericCellValue());
                    DecimalFormat format = new DecimalFormat("0");
                    return format.format(cell.getNumericCellValue()).replaceAll("\\s*", "");
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue()).replaceAll("\\s*", "");
            case FORMULA:
                return cell.getCellFormula();
            default:
                return null;
        }
    }


    public static double getCellNumericValue(Cell cell) {
        if (cell == null || cell.getCellType() != CellType.NUMERIC) {
            return 0;
        }
        return cell.getNumericCellValue();
    }


}
